package cn.itcast.nio.c3;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

import static cn.itcast.nio.c1.ByteBufferUtil.debugRead;

/**
 * 非阻塞模式服务器端
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        //0.ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //1.创建了服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //切换非阻塞模式
        ssc.configureBlocking(false);
        //2.绑定监听端口
        ssc.bind(new InetSocketAddress(8080));
        //3.连接集合
        ArrayList<SocketChannel> channels = new ArrayList<>();
        //4.accept
        while (true){
            //建立于客户端连接,SocketChannel用来与客户端通信
            SocketChannel sc = ssc.accept();//非阻塞方法 如果没有建立连接 sc = null
            if(sc != null){
                log.debug("connected...{}",sc);
                channels.add(sc);
            }
            for(SocketChannel channel:channels){
                //接受客户端的数据
                //
                channel.configureBlocking(false);
                int len = channel.read(buffer);//非阻塞方法,如果没有读到数据,read 返回 0
                if(len > 0){
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("afterRead...");
                }
            }
        }
    }
}
